package api

import (
	"context"
	"dogapm"
	"github.com/google/uuid"
	"net/http"
	"ordersvc/dao"
	"ordersvc/grpcclient"
	"proto"
	"strconv"
)

type order struct {
}

var Order = &order{}

func (o *order) Add(w http.ResponseWriter, request *http.Request) {

	// 获取参数
	values := request.URL.Query()
	var (
		uid, _   = strconv.Atoi(values.Get("uid"))
		skuid, _ = strconv.Atoi(values.Get("sku_id"))
		num, _   = strconv.Atoi(values.Get("num"))
	)

	ctx, span := dogapm.Tracer.Start(context.TODO(), "createOrder")
	defer span.End()

	//   检查用户信息
	_, err := grpcclient.UserClient.GetUsersInfo(ctx, &proto.User{
		Id: int64(uid),
	})
	if err != nil {
		dogapm.Logger.Error(ctx, "createOrder", map[string]interface{}{
			"uid":    uid,
			"sku_id": skuid,
		}, err)
		dogapm.HttpStatus.Error(w, err.Error(), nil)
		return
	}

	//   对库存进行扣减
	skuMsg, err := grpcclient.SkuClient.DecreaseStock(ctx, &proto.Sku{
		Id:  int64(skuid),
		Num: int32(num),
	})

	if err != nil {
		dogapm.Logger.Error(ctx, "createOrder", map[string]interface{}{
			"uid":    uid,
			"sku_id": skuid,
		}, err)
		dogapm.HttpStatus.Error(w, err.Error(), nil)
		return
	}

	// 创建订单
	order := dao.OrderDao{}
	err = order.Create(dao.OrderDao{
		OrderId: uuid.New().String(),
		Num:     int32(num),
		Price:   skuMsg.Price,
		SkuId:   int64(skuid),
		Uid:     int64(uid),
	})

	if err != nil {
		dogapm.Logger.Error(ctx, "createOrder", map[string]interface{}{
			"uid":    uid,
			"sku_id": skuid,
		}, err)
		dogapm.HttpStatus.Error(w, err.Error(), nil)
		return
	}
	dogapm.HttpStatus.Ok(w)
}
